import { _decorator, Component, Vec3, SkeletalAnimationComponent } from 'cc';
import { nUtils } from '../../../libs/nUtils';

const { ccclass, property } = _decorator;
// Animation Const
const idle = "idle"
const run = "run"

@ccclass('NavMeshAgent')
export class NavMeshAgent extends Component {
	/* 可否移动 */
	private move = false;
	/* 路线 */
	private _path = [];
	/* 移速 */
	private speed = 10;
	/* 欧拉角度Y */
	private roleAngel = 0
	private step = 0
	private currstep = null
	/* 骨骼动画组件 */
	private anm: SkeletalAnimationComponent = null;
	/* 保存当前动画名 */
	private anmName = null;

	private pos:Vec3=new Vec3();
	private des:Vec3=new Vec3();



	onEnable() {
		this.anm = this.node.getComponent(SkeletalAnimationComponent);
		this.anmName = null;
		this.playLoopAnm("idle");
		this.speed = 5 + 15 * Math.random()
	}

	onDisable() {
		this.move = false;
		this.anm = null;
		this._path.length=0;
		this.currstep = null;
		this.step = 0;
	}

	playLoopAnm(name: string):void {
		// if (this.anmName == name) return
		// this.anm.play(name);
		// this.anmName = name;
	}

	startMove(path):void  {
            this.stopMove();
			this._path = path;
			this.move = true;
	}

	stopMove():void {
		this.move = false;
		this._path.length=0;
		this.step = 0;
		this.currstep = null;
		this.playLoopAnm(idle);

	}


	update(dt) {
		if (this.move) {
			this.playLoopAnm(run);
			this.pos.set(this.node.position) 
			if (this.currstep != this.step) {
				this.des.set(this._path[this.step]) ;
				this.rotateRole(this.pos, this.des);
				this.currstep = this.step;
			}
			if (nUtils.MoveTowards(this.pos, this.pos, this.des, dt * this.speed)) this.changeStep();
			this.node.setPosition(this.pos)
		}
	}

	changeStep():void  {
		this.step++
		if (this.step == this._path.length) {
			this.playLoopAnm("idle");
			this.move = false
		}
	}

	/**
	 * @Date: 2022-02-1 01:26:04
	 * @LastEditors: iwae
	 * @description: 水平方向面对目标
	 * @param {Vec3} pos 转向节点位置
	 * @param {Vec3} target 目标位置
	 */
	rotateRole(pos: Vec3, target: Vec3):void  {
		this.roleAngel = (Math.atan2(target.x - pos.x, target.z - pos.z) * (180 / Math.PI)) % 360;
		//角色转动的角度,相对Z轴，逆时针为正方向
		this.node.setRotationFromEuler(0, this.roleAngel);
	}


}

